package com.xfs.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.xfs.entity.po.ExcelData;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author dwj
 * @Date 2022-05-25 22:29
 */
@Slf4j
public class ExcelListener extends AnalysisEventListener<ExcelData> {
    private static final int BATCH_COUNT = 100;
    List<ExcelData> list = new ArrayList<>();

    @Override
    public void invoke(ExcelData excelData, AnalysisContext analysisContext) {
        log.info("解析到一条数据");
//        log.info("解析到一条数据:{}", JSONObject.toJSON(excelData));
        list.add(excelData);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成");
    }

    /**
     * 存储数据库
     */
    private void saveData(){
        log.info("{}条数据，开始存储数据库！", list.size());
        log.info("存储数据库成功！");
    }
}
